package com.example.tys.baseapplication.View.banner;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.MainThread;
import android.support.v4.view.VelocityTrackerCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tys on 2017/10/9.
 */

public abstract class BannerCore extends ViewGroup {
    private int childCount;
    private int childWidth;
    private int childHeight;
    private int index;
    private boolean isAutoScan = true;
    private float startX;//down,移动前位置
    private boolean isClick;
    private BannerViewOnClickListen clickListen;
    private VelocityTracker mVelocityTracker;
    private int mMaximumVelocity;
    private int mMinimumVelocity;
    private final WeakReference<BannerCore> mThisWeakRef = new WeakReference<>(this);
    private Handler handler = new MyHandler(mThisWeakRef);
    private Timer timer;

    static class MyHandler extends Handler {
        WeakReference<BannerCore> view;
        MyHandler(WeakReference<BannerCore> view) {
            this.view = view;
        }
        @Override
        public void handleMessage(Message msg) {
            BannerCore bannerCore= view.get();
            if(bannerCore != null){
                if (bannerCore.isAutoScan) {
                    if (++bannerCore.index >= bannerCore.childCount)
                        bannerCore.index = 0;
                    bannerCore.scrollTo(bannerCore.index * bannerCore.childWidth, 0);
                    bannerCore.bannerImagePosition(bannerCore.index);
                }
            }
        }
    }

    public BannerCore(Context context) {
        this(context, null);
    }

    public BannerCore(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerCore(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        timer = new Timer(true);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 5000, 5000);
        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
        mMinimumVelocity = (int) (400 * getResources().getDisplayMetrics().density);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (changed) {
            for (int i = 0; i < childCount; i++) {
                View view = getChildAt(i);
                int indexStart = i * childWidth;
                view.layout(indexStart, 0, indexStart + childWidth, childHeight);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        childCount = getChildCount();
        if (childCount > 0) {
            measureChildren(widthMeasureSpec, heightMeasureSpec);
            View childView = getChildAt(0);
            childWidth = childView.getMeasuredWidth();
            childHeight = childView.getMeasuredHeight();
            setMeasuredDimension(childWidth * childCount, childHeight);
        } else {
            setMeasuredDimension(0, 0);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                isAutoScan = false;
                isClick = true;
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                float difX = startX - moveX;
                scrollBy((int) difX, 0);
                startX = moveX;
                isClick = false;
                break;
            case MotionEvent.ACTION_UP:
                int scrollX = getScrollX();
                index = (scrollX + childWidth / 2) / childWidth;
                if (isClick) {//单击
                    if (clickListen != null) clickListen.onClick(index);
                } else {//滑动
                    final VelocityTracker velocityTracker = mVelocityTracker;
                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                    int initialVelocity = (int) velocityTracker.getXVelocity();
                    if (Math.abs(initialVelocity) > mMinimumVelocity) {
                        index = initialVelocity > 0 ? --index : ++index;
                    }
                    if (index >= childCount) {
                        index = childCount - 1;
                    } else if (index <= 0) {
                        index = 0;
                    }
                    scrollTo(index * childWidth, 0);
                    bannerImagePosition(index);
                }
                isAutoScan = true;
                break;
        }
        return true;
    }

    public void setAutoScan(boolean autoScan) {
        isAutoScan = autoScan;
    }

    public void cancelImageScan(){
        timer.cancel();
    }

    public void setBannerViewClickListen(BannerViewOnClickListen clickListen) {
        this.clickListen = clickListen;
    }

    interface BannerViewOnClickListen {
        void onClick(int index);

    }

    abstract void bannerImagePosition(int position);

}


